// 2025/2/18: 首个版本

using System;
using Eto.Forms;
using ASEva.UIEto;
using Eto.Drawing;

namespace CommonSource
{
    class InputNumberOrString : DialogPanel
    {
        public InputNumberOrString(String title, double defaultValue, Icon icon = null)
        {
            Icon = icon;
            Title = title;
            SetFixMode(600, 50, true);

            InputValue = defaultValue.ToString();

            var layout = this.SetContentAsRowLayout();
            var textBox = layout.AddControl(new TextBox{ Text = InputValue }, true);
            var button = layout.AddButton("OK", false, 80);

            textBox.TextChanged += delegate
            {
                double num = 0;
                if (Double.TryParse(textBox.Text, out num))
                {
                    textBox.TextColor = SystemColors.ControlText;
                    button.Enabled = true;
                }
                else
                {
                    textBox.TextColor = Colors.Red;
                    button.Enabled = false;
                }
            };

            initEvents(textBox, button);
        }

        public InputNumberOrString(String title, String defaultValue, Icon icon = null)
        {
            Icon = icon;
            Title = title;
            SetFixMode(600, 50, true);

            InputValue = defaultValue;

            var layout = this.SetContentAsRowLayout();
            var textBox = layout.AddControl(new TextBox{ Text = InputValue }, true);
            var button = layout.AddButton("OK", false, 80);

            initEvents(textBox, button);
        }

        private void initEvents(TextBox textBox, Button button)
        {
            Shown += delegate
            {
                textBox.Focus();
            };

            textBox.KeyDown += (o, e) =>
            {
                if (e.Key == Keys.Enter && button.Enabled)
                {
                    InputValue = textBox.Text;
                    Close();
                }
            };

            button.Click += delegate
            {
                InputValue = textBox.Text;
                Close();
            };
        }

        public String InputValue { get; private set; }
    }
}